from datetime import datetime

from api.search.utils import activity_import, role_import
from config import client, col_activity, col_register, col_institution
from api.search.mapping_region import mapping_region
from api.search.schema_act_member import Activity

activity_col = col_activity
member_col = col_register
inst_col = col_institution


def clean_region(region):
    if not region:
        return "", "", ""

    if region:
        province = region.get("province")
        city = region.get("city")
        district = region.get("district")
        return province, city, district


def region_map(region):
    if not region:
        return ""
    province = region.get("province")
    if not province:
        return ""
    for k, v in mapping_region.items():
        checker = [item for item in v if province.strip() in item]
        if checker:
            return k


def clean_media(media):
    data = []
    if not media:
        return []
    for med in media:
        data.append(med.get("path"))
    return data


def clean_dept(dept):
    if not isinstance(dept, list):
        dept = [dept]
    institutions = inst_col.find({"_id": {"$in": dept}}, {"institution_name": 1})
    data = []
    for inst in institutions:
        _kx = inst.get("level", -1)
        is_kx = True if _kx >= 0 else False
        data.append({"id": str(inst["_id"]), "institution_name": inst['institution_name'], "is_kexie": is_kx})
    return data


def import_activity_members():
    for act in activity_col.find({"is_deleted": {"$ne": True}}):
        _year = act['end_time'].year if isinstance(act['end_time'], datetime) else None
        activity = Activity(
            _id=str(act.get("_id")),
            id=str(act.get("_id")),
            name=act.get('name'),
            start_time=act.get('start_time'),
            end_time=act.get('end_time'),
            range_year=_year,
            abstract=act.get('abstract'),
            activity_type=act.get('activity_type'),
            activity_type_two=act.get('activity_type_two'),
            images=clean_media(act.get('images', [])),
            videos=clean_media(act.get('video', [])),
            province=clean_region(act.get("region"))[0],
            city=clean_region(act.get("region"))[1],
            district=clean_region(act.get("region"))[2],
            update_time=act.get("update_time"),
            update_at=datetime.utcnow(),
            host_label=clean_dept(act['institution_id'])[0],
            coop_labels=clean_dept(act['co_inst_ids']),
            region=region_map(act.get("region", None)),
            importance_of_activities=act.get("importance_of_activities") or '常规',
            # importance_of_activities 可能为空串，所以使用 or 操作符
            activity_tags=act.get("tags", []),
            score_importance_of_activities=activity_import.get(act.get("importance_of_activities", "常规")) or 1,
            meta={"routing": 1}
        )
        activity.save()
        members = member_col.find({"activity_id": act['_id'], "is_attended": True})
        role_score = []
        _number_of_applicants = 0
        for member in members:
            _mapping = {
                "contribution": member.get("contribution"),
                "is_attended": member.get("is_attended"),
                "level_of_role": member.get("level_of_role"),
                "per_act_time": member.get("per_act_time", 0),
                "update_time": member.get("update_time", ),
                "person_id": str(member.get("person_id")),
                "_id": str(member.get("_id")),
                "activity_id": str(member.get("activity_id")),
                "act_type": str(act.get('activity_type')),
                "score_importance_of_activities": activity_import.get(act.get("importance_of_activities", "常规")) or 1,
                "score_importance_of_role": role_import.get(member.get("level_of_role", "一般参与")),
                "update_at": datetime.utcnow(),
            }
            activity.add_member(_mapping)
            _number_of_applicants += 1
        activity.number_of_applicants = _number_of_applicants
        activity.save()
        print("1")

if __name__ == '__main__':
    import_activity_members()